package com.example.zcq.rxjava2retrofitmvp.httpservice;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author zcq
 * @package com.example.zcq.rxjava2retrofitmvp.net
 * @fileName Rxjava2RetrofitMVP
 * @description: 获取代理对象
 * @org 融信通达科技有限公司
 * @email @163.com
 * @date 2018/9/19  21:47
 */
public class NetWorkRetrofit {
    private static NetWorkRrtrofitInterface singleton;


    public static NetWorkRrtrofitInterface getRetrofit(OkHttpClient client) {
        if (singleton == null) {
            synchronized (NetWorkRetrofit.class) {
                singleton = createRetrofit(client).create(NetWorkRrtrofitInterface.class);
            }
        }
        return singleton;
    }

    //*********************************************************************
    //另一种单例模式
    //不用传OkHttpClient
    public static NetWorkRrtrofitInterface getSimpleRetrofit() {
        return Holder.INSTANCE;
    }

    private static class Holder {
        private static final NetWorkRrtrofitInterface INSTANCE = createRetrofit(new OkHttpClient.Builder().build()).create(NetWorkRrtrofitInterface.class);
    }
    //*********************************************************************

    /**
     * 创建Retrofit实例
     *
     * @param client
     * @return
     */
    private static Retrofit createRetrofit(OkHttpClient client) {
        //        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        //        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://ixiangni.cn/ixiangni/")//    Retrofit2 的baseUlr 必须以 /（斜线） 结束，不然会抛出一个IllegalArgumentException
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(client)
                .build();
        return retrofit;
    }

    /**
     * 多个流重复利用一系列操作符
     * 指定事件发送者为新线程，接收者为主线程
     *
     * @param <T>
     */
    public static final class NetWorkTransformer<T> implements ObservableTransformer<T, T> {

        @Override
        public ObservableSource<T> apply(Observable<T> upstream) {
            return upstream
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread());
        }
    }
}
